import { reactive, computed, watchEffect } from 'vue'

const getTodoList = () => JSON.parse(localStorage.getItem('LOCALTODOLIST') || '[]')
const setTodoList = (arr) => localStorage.setItem('LOCALTODOLIST', JSON.stringify(arr))

export const todoState = reactive({
  todoList: getTodoList(),
  todoCompleteList: computed(() => todoState.todoList.filter((item) => item.checked)),
  todoWorkingList: computed(() => todoState.todoList.filter((item) => !item.checked)),
  changeTodoList: (content) => {
    if (!content) return
    todoState.todoList.push({
      checked: false,
      content: content,
      id: Math.random()
    })
    // setTodoList(todoState.todoList)
  },
  toogleChecked: (index) => {
    const nowIndex = todoState.todoList.findIndex((item) => item.id === index)
    todoState.todoList[nowIndex].checked = !todoState.todoList[nowIndex].checked
    // setTodoList(todoState.todoList)
  },
  deleteItem: (index) => {
    const nowIndex = todoState.todoList.findIndex((item) => item.id === index)
    todoState.todoList.splice(nowIndex, 1)
    // setTodoList(todoState.todoList)
  }
})

watchEffect(() => {
  setTodoList(todoState.todoList)
})

